#encoding=utf8
'''
Created on Oct 21, 2014

@author: jingyang <jingyang@smalltreemedia.com>
'''
import random
import string
import urllib
import urllib2
import json

from django.http.response import HttpResponseRedirect
from django.contrib import messages, auth
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.core.urlresolvers import reverse

from accounts import jwt_lib
import settings


CLIENT_ID = settings.CLIENT_ID
CLIENT_SECRET = settings.CLIENT_SECRET
REDIRECT_URL = settings.REDIRECT_URL
AUTH_URL = settings.AUTH_URL
ADMIN_EMAIL = settings.MANAGERS[0][1]
GET_TOKEN_URL = settings.GET_TOKEN_URL


def login(req):
    write_admin = False
    if req.user.is_authenticated():
        if req.user.is_active:
            return HttpResponseRedirect(req.REQUEST.get('next', '/'))
        else:
            messages.error(req, 'Account Disabled.')
            write_admin = True
    auth.logout(req)
    security_token = ''.join(random.choice(string.ascii_uppercase + string.digits)
        for x in xrange(32))
    req.session['st'] = security_token
    return render_to_response('common.html', RequestContext(req,
        {'title': "Sign in",
         'client_id': CLIENT_ID, 'security_token': security_token,
         'redirect_uri': REDIRECT_URL, 'auth_url': AUTH_URL,
         'scope': 'openid email', 'write_admin': write_admin,
         'admin': ADMIN_EMAIL}))


def checkauth(req):
    state = req.REQUEST.get('state')
    try:
        security_token = state.split('&')[0].split('=')[1]
        from_url = state.split('&')[1].split('=')[1]
    except:
        messages.error(req, 'Auth Failed.')
        return render_to_response('redir.html')
    if not security_token == req.session.get('st'):
        messages.error(req, 'Security Token Error.')
        return render_to_response('redir.html')
    error = req.REQUEST.get('error')
    if error == 'access_denied':
        messages.error(req, 'Login Cancel.')
        return render_to_response('redir.html')
    code = req.REQUEST.get('code')
    params = urllib.urlencode({'code': code, 'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET, 'grant_type': 'authorization_code',
        'redirect_uri': REDIRECT_URL})
    try:
        request = urllib2.urlopen(GET_TOKEN_URL, params)
        response = json.loads(request.read())
        id_token = response.get('id_token')
        info = jwt_lib.decode(id_token, verify=False)
        user, _ = auth.models.User.objects.get_or_create(email=info.get('email'),
            defaults={'username': info.get('email').partition('@')[0],
                      'is_active': False, 'password': ' '})
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        auth.login(req, user)
        return render_to_response('redir.html')
    except Exception, e:
        print e
        messages.error(req, 'Get Token Failed')
        return render_to_response('redir.html')


def redirect(req, path):
    return HttpResponseRedirect('http://%s?%s' % (path,
        req.META.get('QUERY_STRING', '')))


def default(req):
    return HttpResponseRedirect(reverse(login))
